var express = require('express');
let mysqlExec = require('../db/dbMySql.js');
let { Msg, curPath,useJWT } = require('../tools/msg.js');

const { v4: uuidv4 } = require('uuid');
var router = express.Router();


//报名学习接口：
router.post('/study', async(req, res) => {

    //接参
    //课程id
    let { cid = '', jwtData } = req.body;
    if (cid == '') {
        res.send(Msg(500, '课程id不能为空'));
        return;
    }

    //使用JWT数据：
    let jwtObj = useJWT(jwtData);
    if (!jwtObj) {
        res.send(Msg(505, '非法访问请登录'));
        return;
    }

    //查询当前课程是否报名学习过：
    let sql = `select count(id) as m from e_order where cid='${cid}' and mid='${jwtObj.uid}'`;
    let [e, d] = await mysqlExec(sql);
    if (d[0].m == 1) {
        res.send(Msg(500, '已报名学习过！'));
        return;
    }

    //
    sql = `insert into e_order(oid,cid,mid,createdate,status)values('${uuidv4()}','${cid}','${jwtObj.uid}','${new Date().getTime()}','1')`;
    let [err, data] = await mysqlExec(sql);
    if (err && data.affectedRows == 1) {
        res.send(Msg(200, '报名学习成功'));
    } else {
        res.send(Msg(500, '报名学习失败'));
    }

});

//根据课程id查询课程的详细数据：
router.get('/details', async(req, res) => {

    //接参(课程id)
    let { cid = '' } = req.query;
    if (cid == '') {
        res.send(Msg(500, '课程id不能为空'));
        return;
    }

    //根据课程id查询课程及老师的相关数据：
    let sql = `select cid,title,price,c.intro,concat('${curPath}course/',detail_imgs) as detail_imgs,area_name,grade_name,subject_name,realname,t.intro as tintro,head_photo_url from e_course as c left join e_teacher as t on c.tid=t.tid  where cid='${cid}'`;
    let [err, datas] = await mysqlExec(sql);

    //根据课程id查询课程的视频相关数据：
    sql = `select * from e_video where cid='${cid}'`;
    let [e, d] = await mysqlExec(sql);
    if (e) {
        datas.unshift(d);
    } else {
        datas.unshift([]);
    }

    if (err) {
        res.send(Msg(200, '课程详细数据查询成功', datas));
    } else {
        res.send(Msg(500, '课程详细数据查询失败'));
    }
});

module.exports = router;